package jsj.open.lib.fileview

import android.os.Environment
import android.util.Log
import java.io.File

class FileExploer {
    private var rootPath:String=  Environment.getExternalStorageDirectory().absolutePath

    private var current:Node?=null
    private var allPath = rootPath
    private var currentFold:String = ""
    var onPathChange:((String,String)->Unit)?=null
    fun explode(path: String = rootPath): MutableList<FileBean> {
        if (!isPathValid(path)) {
            throw java.lang.RuntimeException("路径错误")
        }
        val file = File(path)
        val list = mutableListOf<FileBean>()
        file.listFiles()?.forEach {
//            Log.e("TAG", "explode: ${it.name}", )
            list.add(FileBean(it.name, it.absolutePath,it.isDirectory))
        }
        list.sortBy { it.name } // 在原列表上排序
        current = Node()
        current!!.files = list
        current!!.file =file
        currentFold = ""
        allPath = file.path
        onPathChange?.let {
            it(allPath,currentFold)
        }
        return list
    }
    fun jump(path: String): MutableList<FileBean> {
        if (!isPathValid(path)) {
            throw java.lang.RuntimeException("路径错误")
        }
        val file = File(path)
        if(file.isDirectory){
            currentFold = file.name
            allPath = file.path.replace(file.name,"")
        }else{
            return mutableListOf()
        }
        val list = mutableListOf<FileBean>()
        file.listFiles()?.forEach {
//            Log.e("TAG", "jump: ${it.name}", )
            list.add(FileBean(it.name, it.absolutePath,it.isDirectory))
        }
        list.sortBy { it.name } // 在原列表上排序
        var node = Node()
        node.files = list
        node.file = file
        node.front = current
        current?.next = node
        current = node
        onPathChange?.let {
            it(allPath,currentFold)
        }
        return list
    }
    fun isPathValid(path: String): Boolean {
        val file = File(path)
        return file.exists() && file.canonicalPath == file.absolutePath
    }

    fun back(): Collection<FileBean>? {
        val files = current?.front?.files
        files?.let {
            current!!.next = current
            current = current!!.front
            val file = current!!.file!!
            allPath = file.path.replace(file.name,"")
            currentFold = file.name
        }
        onPathChange?.let {
            it(allPath,currentFold)
        }
        return files
    }
}